#pragma once

#include <iostream>
#include "TcpServer.hpp"

// #include "Protocol.hpp"

#include <signal.h>

#include "Task.hpp"
#include "ThreadPool.hpp"

#define PORT 8081

class HttpServer
{
public:
    HttpServer(int _port = PORT)
        :port(_port),stop(false)
    {}
    ~HttpServer()
    {}
public:
    void InitHttpServer()
    {
        signal(SIGPIPE, SIG_IGN);   // 信号SIGPIPE需要进行忽略，如果不忽略，在写入的时候，可能直接崩溃server
        // tcp_server = TcpServer::GetInstance(port);
    }
    void Loop()
    {
        TcpServer *tsvr = TcpServer::GetInstance(port);
        LOG(Info, "Loop Begin...");
        // int listen_sock = tcp_server->Sock();
        while(!stop)
        {
            // 服务器一直循环运行
            struct sockaddr_in peer;    // 远端
            socklen_t len = sizeof(peer);
            int sock = accept(tsvr->Sock(), (struct sockaddr*)&peer, &len);
            if(sock < 0)
            {
                continue;
            }
            LOG(Info, ">>>>>>>>>-------- Get a link ------<<<<<<<<");
            
            // int* _sock = new int(sock);
            // pthread_t tid;
            // pthread_create(&tid, nullptr, Entrance::HandlerRequest, _sock);
            // pthread_detach(tid);

            Task task(sock);
            ThreadPool::GetInstance()->PushTask(task);
        }
    }

private:
    int port;
    // TcpServer* tcp_server;
    bool stop;

    // ThreadPool thread_pool;
};
